package com.laowang.project.system.controller;

import java.util.*;

import com.github.pagehelper.PageHelper;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * 商家管理Controller
 *
 * @author laowang
 * @date 2023-04-18
 */
@Api(tags = "商家管理接口")
@RestController
@RequestMapping("/shop")
public class MyCyhShopController extends BaseController {
    @Autowired
    private MyCyhShopService myCyhShopService;

    @Autowired
    private MyCyhShopCateService myCyhShopCateService;

    @Autowired
    private MyBrandService myBrandService;

    @Autowired
    private MyCyhImgService myCyhImgService;


    @Autowired
    private MyCyhShopCattleService myCyhShopCattleService;

    @Autowired
    private MyProductService myProductService;

    @Autowired
    private MyCouponService myCouponService;

    @ApiOperation(value = "小程序端 查询自己的店铺",notes = "")
    @GetMapping("/my")
    public AjaxResult my() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        List<MyCyhShop> myCyhShops = myCyhShopService.selectMyCyhShopByUserId(mid);
        return AjaxResult.success("操作成功",myCyhShops);
    }


    /**
     * 查询商家管理列表
     */
    @ApiOperation(value = "小程序端 查询商家管理列表",notes = "")
    @GetMapping("/shopList")
    public TableDataInfoMy shopList(MyCyhShop myCyhShop) {
        Integer m = 0;
        MyBrand myBrand = myBrandService.selectMyBrandById(1);
        if (myBrand !=null){
            m = myBrand.getSort();
        }
        List<MyCyhShop> list =new ArrayList<>();
        startPage();
        if (m.equals(0)){
            list = myCyhShopService.selectMyCyhShopListWeb(myCyhShop);

        }else if (m.equals(1)){
            //浏览量
            list =  myCyhShopService.selectMyCyhShopListWebSortOne(myCyhShop);

        }else if (m.equals(2)){
            //商家级别
            list =  myCyhShopService.selectMyCyhShopListWebSortTwo(myCyhShop);
        }


        for (MyCyhShop cyhImg : list) {
            if (cyhImg.getPlanId() !=null){
                if (cyhImg.getId().equals(1)){
                    cyhImg.setPlanName("联盟商家");
                }else if (cyhImg.getPlanId().equals(2)){
                    cyhImg.setPlanName("精选商家");
                }else if (cyhImg.getPlanId().equals(3)){
                    cyhImg.setPlanName("理事商家");
                }
            }
        }
        return getDataTableMy(list);
    }

    @ApiOperation(value = "小程序端 查询商家详情",notes = "")
    @GetMapping("/detail/{id}")
    public AjaxResult shopList(@PathVariable Integer id) {

        MyCyhShop myCyhShop = myCyhShopService.selectMyCyhShopById(id);
        return AjaxResult.success("操作成功",myCyhShop);
    }

    @ApiOperation(value = "小程序端 商家入驻",notes = "")
    @PostMapping("/settle")
    public AjaxResult settle(@RequestBody MyCyhShop myCyhShop) {
        if (Objects.isNull(myCyhShop.getPlanId()) ){
            return AjaxResult.error("方案不能为空");
        }

        if (myCyhShop.getShopCattleId()== null){
            return AjaxResult.error("铺信息不能为空");
        }

        MyCyhShopCattle myCyhShopCattle = myCyhShopCattleService.selectMyCyhShopCattleById(myCyhShop.getShopCattleId());
        if (myCyhShopCattle== null){
            return AjaxResult.error("铺信息不存在");
        }
        Integer pay = myCyhShopCattle.getPay();
        if (!pay.equals(1)){
            return AjaxResult.error("铺未支付");
        }
        /*MyCyhShop myCyhShop1 = new MyCyhShop();
        myCyhShop1.setShopCattleId(myCyhShopCattle.getId());
        List<MyCyhShop> myCyhShops = myCyhShopService.selectMyCyhShopList(myCyhShop1);*/

        if (myCyhShopCattle.getIsOpen()>= myCyhShopCattle.getNumber()){
            return AjaxResult.error("开店已满");
        }

        MyCyhImg cyhImg = myCyhImgService.selectMyCyhImgById(myCyhShop.getPlanId());
        if (cyhImg == null){
            return AjaxResult.error("商家方案不存在");
        }
        myCyhShop.setExpireTime(myCyhShopCattle.getEndTime());
        int i = myCyhShopService.insertMyCyhShopWeb(myCyhShop);
        if (i >0){
            Integer isOpen = myCyhShopCattle.getIsOpen();
            isOpen++;
            myCyhShopCattle.setIsOpen(isOpen);
            myCyhShopCattleService.updateMyCyhShopCattle(myCyhShopCattle);
        }
        return AjaxResult.success("操作成功",i);
    }

    @ApiOperation(value = "小程序端 修改商家信息",notes = "")
    @PostMapping("/web/edit")
    public AjaxResult shopEdit(@RequestBody MyCyhShop myCyhShop) {
        Integer id = myCyhShop.getId();
        if (Objects.isNull(id   )){
            return AjaxResult.error("店铺详情id 不能为空");
        }

        Integer userId = myCyhShop.getUserId();
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        if (!userId.equals(mid)){
            return AjaxResult.error("商家归属人不相符");
        }
        myCyhShopService.shopEdit(myCyhShop);
        return AjaxResult.success("操作成功");
    }


    @ApiOperation(value = "商家端 修改商家信息",notes = "")
    @PostMapping("/merchant/edit")
    public AjaxResult shopEdit1(@RequestBody MyCyhShop myCyhShop) {
        Integer id = myCyhShop.getId();
        if (Objects.isNull(id   )){
            return AjaxResult.error("店铺详情id 不能为空");
        }


        myCyhShopService.shopEdit(myCyhShop);
        return AjaxResult.success("操作成功");
    }

    @ApiOperation(value = "商家端 今日营业额",notes = "")
    @GetMapping("/merchant/turnover")
    public AjaxResult turnover(Integer shopId,String date,Integer pageNum ,Integer pageSize,Integer type ) {

        if (shopId == null){
            return AjaxResult.error("店铺详情id 不能为空");
        }
        if (pageNum ==  null && pageSize == null){
            pageNum = 1;
            pageSize = 10;
        }

        if (type.equals(1)){
            //优惠券
            PageHelper.startPage(pageNum,pageSize);
            List<MyProduct> myProductList =  myProductService.selectMyProductListWeb(shopId,date);
            Integer  count = myProductService.selectCount(shopId, date);
            Map<String,Object> map =new HashMap<>();
            map.put("list",myProductList);
            map.put("amount",count);
            return AjaxResult.success("操作成功",map);
        }else if (type.equals(2)){
            //团购商品
            PageHelper.startPage(pageNum,pageSize);
            List<MyCoupon>  myCouponList =  myCouponService.selectMyCouponWeb(shopId, date);
            Integer  count = myCouponService.selectCount(shopId, date);
            Map<String,Object> map =new HashMap<>();
            map.put("list",myCouponList);
            map.put("amount",count);
            return AjaxResult.success("操作成功",map);

        }

        return AjaxResult.error("操作失败");
    }

    /**
     * 查询商家管理列表
     */
    @ApiOperation(value = "后台管理 查询商家管理列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shop:list')")
    @GetMapping("/list")
        public TableDataInfo list(MyCyhShop myCyhShop) {
        startPage();
        List<MyCyhShop> list = myCyhShopService.selectMyCyhShopList(myCyhShop);
        List<MyCyhShopCate> myCyhShopCates = myCyhShopCateService.selectMyCyhShopCateList(null);
        for (MyCyhShop cyhShop : list) {
            for (MyCyhShopCate myCyhShopCate : myCyhShopCates) {
                if (cyhShop.getCate().equals(myCyhShopCate.getId())){
                    cyhShop.setCateStr(myCyhShopCate.getTitle());
                }
            }
            if (cyhShop.getPlanId() !=null){
                if (cyhShop.getPlanId().equals(1)){
                    cyhShop.setPlanName("联盟商家");
                }else if (cyhShop.getPlanId().equals(2)){
                    cyhShop.setPlanName("精选商家");
                }else if (cyhShop.getPlanId().equals(3)){
                    cyhShop.setPlanName("理事商家");
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出商家管理列表
     */
    //@ApiOperation(value = "后台管理 导出商家管理列表",notes = "")
    //@PreAuthorize("@ss.hasPermi('my:shop:export')")
    //@Log(title = "商家管理", businessType = BusinessType.EXPORT)
    //@GetMapping("/export")
    public AjaxResult export(MyCyhShop myCyhShop) {
        List<MyCyhShop> list = myCyhShopService.selectMyCyhShopList(myCyhShop);
        ExcelUtil<MyCyhShop> util = new ExcelUtil<MyCyhShop>(MyCyhShop.class);
        return util.exportExcel(list, "shop");
    }

    /**
     * 获取商家管理详细信息
     */
    @ApiOperation(value = "后台管理 获取商家管理详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shop:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhShopService.selectMyCyhShopById(id));
    }


    /**
     * 新增商家管理
     */
    @ApiOperation(value = "后台管理 新增商家管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shop:add')")
    @Log(title = "商家管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhShop myCyhShop) {
        return toAjax(myCyhShopService.insertMyCyhShop(myCyhShop));
    }

    /**
     * 修改商家管理
     */
    @ApiOperation(value = "后台管理 修改商家管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shop:edit')")
    @Log(title = "商家管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhShop myCyhShop) {
        return toAjax(myCyhShopService.updateMyCyhShop(myCyhShop));
    }

    /**
     * 删除商家管理
     */
    @ApiOperation(value = "后台管理 删除商家管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shop:remove')")
    @Log(title = "商家管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhShopService.deleteMyCyhShopByIds(ids));
    }
}
